package com.yc.navy.snacknet.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.navy.snacknet.vo.ResultVO;


public class BaseController extends HttpServlet{

	private static final long serialVersionUID = -3151325301425489392L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//原本是在这个里面判断请求的类型，如果是GTE请求则调用doGet()，如果是Post请求则调用dopost()

		//获取请求路径
		String url = request.getRequestURI();
		System.out.println(url);
		//获取最后一节路径 ->
		String path = url.substring(url.lastIndexOf("/") + 1);
		
		//
		Method[] methods = this.getClass().getDeclaredMethods();
		
		for(Method method : methods) {
			if(path.equals(method.getName())) {
			
				try {
					method.invoke(this, request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
		}
		this.error(request, response);
 	}

	/**
	 * 响应
	 * @param response
	 * @param code
	 * @param msg
	 * @param obj
	 * @throws IOException
	 */

	protected void send(HttpServletResponse response, ResultVO resultVO) throws  IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		ObjectMapper mapper = new ObjectMapper();
		out.print(mapper.writeValueAsString(resultVO));
		out.flush();
		out.close();
	}

	protected void send(HttpServletResponse response, int code, String msg) throws  IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", code);
		map.put("msg", msg);
		out.print(mapper.writeValueAsString(map));
		out.flush();
		out.close();
	}

	private void error(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html:charset=utf-8");
		PrintWriter out = response.getWriter();
		String basepath = request.getScheme() + "://" +request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
		out.println("<script></script>");
		out.flush();
		out.close();
	}



	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
		
	}



	
	
	
}
